import archiver from "archiver";
import { createWriteStream } from "fs";
import { Options } from "../../types/options";
import { resolveTempFile, resolveWorkspace } from "../../utils/common";
import fs from "fs-extra";
import { CONFIG } from "../../utils/config";

export async function compressFiles(options: Pick<Options, "uploadList">) {
    const { uploadList } = options;

    return await Promise.all(
        uploadList.map(async (upload: Options["uploadList"][number]) => {
            const { fileList } = upload;

            return await Promise.all(
                fileList.map(
                    async (
                        file: Options["uploadList"][number]["fileList"][number]
                    ) => {
                        const { id, localPath, remoteFilename } = file;
                        const archive = archiver("tar");

                        const output = createWriteStream(
                            resolveTempFile(`${id}${CONFIG.ZIP_SUFFIX}`)
                        );

                        archive.pipe(output);

                        /* 如果是文件夹 */
                        const path = resolveWorkspace(localPath);
                        const stats = fs.statSync(path);
                        if (stats.isDirectory()) {
                            archive.directory(path, false);
                        } else if (stats.isFile()) {
                            archive.file(path, {
                                name: remoteFilename,
                            });
                        }
                        await archive.finalize();
                    }
                )
            );
        })
    );
}
